/**
 * 全局配置
 */
var HOST="/protocol";
//var HOST="http://118.24.13.142:8080/protocol";
/**
 * 关ajax缓存
 */
var config={
    token: getCookie("token"),
    username: getSessionStorage("username"),
    // role: getCookie("role"),
}
$(function(){
    $.ajaxSetup ({
        cache: false //关闭AJAX缓存
    });
});
/**
 * 获取cookie
 */
function getCookie(cname)
{
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++)
    {
        var c = $.trim(ca[i]);
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}
function setCookie(cname,cvalue,exdays)
{
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}



/**
 * 登录成功响应函数
 * @param data 返回数据
 * @param textStatus 请求状态
 * @param request 请求对象
 */
function router(data, textStatus, request) {

    //请求成功，返回成功信息并设置token为cookie
    if (data.meta.state == "success") {
        //token用户后面身份验证
        var token = request.getResponseHeader("token");
        var role=data.data.role;
        setSessionStorage("token",token);
        setSessionStorage("username",data.data.username);
        setSessionStorage("createTime",data.data.createTime);

        setCookie("token", token);
        //setCookie("username",data.data.username);
        //setCookie("createTime",data.data.createTime);
        $.ajax({
            url: HOST.concat("/checkFirst?token=") + token,
            type: 'GET',
            data:{
                "username":data.data.username
            },
            async:true,
            success: function(res){
                console.log(res);
                if(res.meta.state=="success"){
                    var loc;//跳转页面地址
                    if("firstlogin"==res["meta"]["message"]){
                        loc= "pswChange.html";
                    }else {
                        //不是第一次登录，才检查是否授权
                        config["permissionState"]=res.data.permissionState;
                        if(res.data.permissionState!=2){
                            //并未授权
                            loc= "askauthorization.html";
                        }else{
                            //授权后，根据用户的角色 跳转到的页面
                            if (role==="operator"){
                                //操作员
                                loc="index.html";
                            }
                            else if (role==="auditor"){
                                //业务审计员
                                loc="auditor.html";
                            }
                            else if (role==="sysAuditor"){
                                //系统审计员
                                loc="systemAuditor.html";
                            }
                            else if (role==="admin"){
                                loc="admin.html";
                            }
                        }
                    }
                    var btn=$('#submit');
                    btn.removeAttr("disabled");
                    //登录提示信息
                    window.alert(data.meta.message);
                    location.href=loc+"?token="+config.token;
                }else{
                    //登录失败执行的函数
                    var btn=$('#submit');
                    btn.removeAttr("disabled");
                    window.alert(res.meta.message);
                }
            },
            error: function(){
                console.log("check error！");
            },
            dataType: "json",
        });
        // setCookie("role",data.data.role);
        //根据用户角色进行页面跳转

    }
    //请求失败，返回失败信息并填入提示栏
    else {
        var btn=$('#submit');
        btn.attr("disabled","false");
        window.alert(data.meta.message);
        location.reload();
        createCode();
    }
}

/**
 * 发出登录请求
 * @param data 表单数据
 * @param callback 成功回调函数
 */
function logIn(data, callback) {
    $.ajax({
        type: "POST",
        url: HOST.concat("/login"),
        contentType: "application/x-www-form-urlencoded",
        data: data,
        dataType: "JSON",
        success: callback,
        error: function () {
            console.error("error!");
        }
    });
}

/**
 * 登录表单提交动作
 */
function submit() {
    //锁定按钮，防止重复提交
    var btn=$('#submit');
    btn.attr("disabled","true");
    //获取用户名密码
    var username = $("#username");
    var password = $("#password");
    //获取提示信息
    var warntext = $('.warn-text');
    warntext.text("");
    if (username.val() == "") {
        username.val("");
        warntext.text("用户名不能为空");
        btn.removeAttr("disabled");
        return;
    }
    if (password.val() == "") {
        password.val("");
        warntext.text("密码不能为空");
        btn.removeAttr("disabled");
        return;
    }
    if ('right'!=validate()){
        //验证码的校验
        btn.removeAttr("disabled");
        return;
    }
    //通过验证码校验

    //加密传输
    //var encryptPwd=encrypt(md5(password.val()+'scuwsn'),"1CF80FC80F94F031D7A3AB60E6481347");
    var encryptPwd=rsaEncrypt(md5(password.val()+'scuwsn'));
    var data = {
        username: username.val(),
        password: encryptPwd,
        timeline: new Date().getTime(),
        flag:true   //flag标识鉴权还是登录操作，为true—>的呢过路
    };
   // var data = {
   //      username: username.val(),
   //      password: password.val(),
   //  };

    //登录函数
    logIn(data, router);
}

function keyLogin(){
    if (event.keyCode==13){
        submit();
    }
}
function clearWarn() {
    var warntext = $('.warn-text');
    warntext.text("");
}

$("#submit").click(function () {
    //前端登录函数
    submit();
});

$('#submit').blur(function () {
    clearWarn();
});
$('body').keydown(function (event) {
    keyLogin();
});

/**
 * Rsa加密
 * */

function rsaEncrypt(word) {
    var jsEncrypt = new JSEncrypt();
    var key = sessionStorage.getItem("publicKey");
    jsEncrypt.setPublicKey(key);
    var encrypted = jsEncrypt.encrypt(word);

    return encrypted.toString();
}

/**
 * aes加密（需要先加载lib/aes/aes.min.js文件）
 * @param word
 * @returns {*}
 */
function encrypt(word,key) {
    var key = CryptoJS.enc.Utf8.parse(key);
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}

/**
 * 解密
 * @param word
 * @returns {*}
 */
function decrypt(word,key) {
    var key = CryptoJS.enc.Utf8.parse(key);
    var decrypt = CryptoJS.AES.decrypt(word, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}


//设置一个全局的变量，便于保存验证码
var code;
function createCode(){
    $("#submit").removeAttr("disabled");
    //首先默认code为空字符串
    code = '';
    //设置长度，这里看需求，我这里设置了4
    var codeV = document.getElementById('code');
    //设置随机字符
    $.ajax({
        url: HOST.concat("/IDCode"),
        type: "GET",
        success: function(datas){
            code = datas.data.IDCode;
            drawPic(code);
        },
        error: function(){
            console.log("请求验证码错误！");
        },
        dataType: "json",
    });

}

//下面就是判断是否== 的代码，无需解释
function validate(){
    //验证的校验
    var warntext = $('.warn-text');
    warntext.text("");
    var result = "";
    var oValue = document.getElementById('codeInput').value.toUpperCase();
    var btn=$('#submit');
    btn.attr("disabled","false");
    if(oValue ==''||oValue==undefined){
        //用户输入验证码
        warntext.text('请输入验证码');
        return;
    }else {
        //输入了验证码
        $.ajax({
            url: HOST.concat("/checkIDCode?code="+oValue),
            type: "GET",
            async: false,
            success: function (datas) {
                result = datas.meta.state;
            },
            error: function(){
                console.log("请求验证码错误！");
            },
            dataType: "json",
        });
        if(result=='success'){
            return 'right';
        }else {
            warntext.text('验证码不正确，请重新输入');
            btn.removeAttr("disabled");
            //重新请求 刷新验证码
            createCode();
            //location.reload();
            return;
        }
    }
}


/**生成一个随机数**/
function randomNum(min,max){
    return Math.floor( Math.random()*(max-min)+min);
}
/**生成一个随机色**/
function randomColor(min,max){
    var r = randomNum(min,max);
    var g = randomNum(min,max);
    var b = randomNum(min,max);
    return "rgb("+r+","+g+","+b+")";
}


/**绘制验证码图片**/
function drawPic(IDCode){
    var canvas=document.getElementById("canvas");
    var width=canvas.width;
    var height=canvas.height;
    var ctx = canvas.getContext('2d');
    ctx.textBaseline = 'bottom';

    /**绘制背景色**/
    ctx.fillStyle = randomColor(180,240); //颜色若太深可能导致看不清
    ctx.fillRect(0,0,width,height);
    /**绘制文字**/

    /*   for(var i=0; i<4; i++){ */
    var txt = IDCode;
    ctx.fillStyle = randomColor(50,160);  //随机生成字体颜色
    ctx.font = randomNum(25,30)+'px SimHei'; //随机生成字体大小
    var x = randomNum(15,20);
    var y = randomNum(30,35);
    //修改坐标原点和旋转角度
    ctx.translate(x,y);
    ctx.fillText(txt, 0,0);
    //恢复坐标原点和旋转角度
    ctx.translate(-x,-y);
    /*    } */
    /* /**绘制干扰线**/
    for(var i=0; i<8; i++){
        ctx.strokeStyle = randomColor(40,180);
        ctx.beginPath();
        ctx.moveTo( randomNum(0,width), randomNum(0,height) );
        ctx.lineTo( randomNum(0,width), randomNum(0,height) );
        ctx.stroke();
    }
    /**绘制干扰点**/
    /*  for(var i=0; i<100; i++){
     ctx.fillStyle = randomColor(0,255);
     ctx.beginPath();
     ctx.arc(randomNum(0,width),randomNum(0,height), 1, 0, 2*Math.PI);
     ctx.fill();
     }  */
}

//设置此处的原因是每次进入界面展示一个随机的验证码，不设置则为空
window.onload = function (){
    createCode();
};

/**
 * 获取加密公钥
 * */

function getPublickey(){
    $.ajax({
        url:HOST.concat("/getpublickey"),
        type:"GET",
        dataType:"json",
        success:function (msg) {
            if(msg.meta.state=="success"){
                //保存公钥
                sessionStorage.setItem("publicKey",msg.data.publicKey);
            }
        }
    });
}

/**
 * 从session中回去元素
 * */
function getSessionStorage(key){
    var val = window.sessionStorage.getItem(key);
    return val==null?"无取值":val;
}

/**
 * 从session设置元素
 * */
function setSessionStorage(key,val){
    window.sessionStorage.setItem(key, val);
}